package com.bonuo.erp.service.impl;

import com.bonuo.erp.domain.Supplier;
import com.bonuo.erp.service.SupplierService;
import com.bonuo.erp.mapper.SupplierMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 供应商管理Service实现类
 * 
 * @author doubao
 */
@Service
public class SupplierServiceImpl implements SupplierService {
    @Autowired
    private SupplierMapper supplierMapper;

    /**
     * 查询供应商列表
     * 
     * @param supplier 供应商
     * @return 供应商集合
     */
    @Override
    public List<Supplier> selectSupplierList(Supplier supplier) {
        return supplierMapper.selectSupplierList(supplier);
    }

    /**
     * 查询供应商详细信息
     * 
     * @param id 供应商ID
     * @return 供应商
     */
    @Override
    public Supplier selectSupplierById(Integer id) {
        return supplierMapper.selectSupplierById(id);
    }

    /**
     * 新增供应商
     * 
     * @param supplier 供应商
     * @return 结果
     */
    @Override
    public int insertSupplier(Supplier supplier) {
        return supplierMapper.insertSupplier(supplier);
    }

    /**
     * 修改供应商
     * 
     * @param supplier 供应商
     * @return 结果
     */
    @Override
    public int updateSupplier(Supplier supplier) {
        return supplierMapper.updateSupplier(supplier);
    }

    /**
     * 删除供应商
     * @param
     * @return 结果
     */
    @Override
    public int deleteSupplierById(Integer id) {
        return supplierMapper.deleteSupplierByIds(id);
    }

    /**
     * 导入供应商数据
     * 
     * @param supplierList 供应商数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importSupplier(List<Supplier> supplierList, Boolean updateSupport, String username) {
        if (StringUtils.isNull(supplierList) || supplierList.size() == 0) {
            throw new ServiceException("导入供应商数据不能为空！");
        }
        System.err.println(username);
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Supplier supplier : supplierList) {
            try {
                // 验证是否存在这个供应商
                Supplier existSupplier = supplierMapper.selectSupplierByName(supplier.getName());
                if (StringUtils.isNull(existSupplier)) {
                    supplier.setTaxRate(convertToIntegerPercentage(supplier.getTaxRate()));
                    supplier.setCreateBy(username);
                    this.insertSupplier(supplier);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、供应商 " + supplier.getName() + " 导入成功");
                } else if (updateSupport) {
                    supplier.setTaxRate(convertToIntegerPercentage(supplier.getTaxRate()));
                    supplier.setCreateBy(username);
                    supplier.setId(existSupplier.getId());
                    this.updateSupplier(supplier);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、供应商 " + supplier.getName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、供应商 " + supplier.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、供应商 " + supplier.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 将税率转换为整数百分比格式
     * @param taxRate 原始税率字符串（支持"0.01"、"1%"、"1.23%"等格式）
     * @return 整数百分比字符串（如"1%"），无法转换时返回null
     */
    public static String convertToIntegerPercentage(String taxRate) {
        if (taxRate == null || taxRate.isEmpty()) {
            return null;
        }

        try {
            // 移除百分号并尝试转换为数字
            String numberPart = taxRate.replace("%", "").trim();
            double value = Double.parseDouble(numberPart);

            // 如果原始值包含百分号，直接取整；否则乘以100后取整
            int percentage = taxRate.contains("%")
                    ? (int) Math.round(value)
                    : (int) Math.round(value * 100);

            return percentage + "%";
        } catch (NumberFormatException e) {
            // 非数字格式，返回原始值或根据业务需求处理
            return taxRate;
        }
    }
}